import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'core/constants/app_constants.dart';
import 'core/di/service_locator.dart';
import 'core/utils/global_error_handler.dart';
import 'core/theme/app_theme.dart';
import 'core/services/call_manager_service.dart';
import 'routes/app_router.dart';

// 全局 Navigator Key，用于在任何页面显示对话框
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 设置全局错误处理
  GlobalErrorHandler.setup();
  
  // 捕获异步错误
  runZonedGuarded(
    () async {
      // Initialize service locator
      await ServiceLocator().init();
      
      // 初始化全局通话管理服务
      await CallManagerService().init(navigatorKey);
      
      runApp(const VioletApp());
    },
    (error, stack) {
      GlobalErrorHandler.handleAsyncError(error, stack);
    },
  );
}

class VioletApp extends StatelessWidget {
  const VioletApp({super.key});

  @override
  Widget build(BuildContext context) {
    final serviceLocator = ServiceLocator();
    
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: serviceLocator.bottomNavProvider),
        ChangeNotifierProvider.value(value: serviceLocator.authViewModel),
        ChangeNotifierProvider.value(value: serviceLocator.contactsViewModel),
        ChangeNotifierProvider.value(value: serviceLocator.homeViewModel),
      ],
      child: ScreenUtilInit(
        designSize: const Size(375, 812),
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context, child) {
          return MaterialApp(
            navigatorKey: navigatorKey, // 使用全局 Navigator Key
            title: '紫罗兰',
            debugShowCheckedModeBanner: false,
            theme: AppTheme.lightTheme,
            builder: (context, widget) {
              return MediaQuery(
                data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
                child: widget!,
              );
            },
            initialRoute: AppConstants.routeSplash,
            onGenerateRoute: AppRouter.generateRoute,
          );
        },
      ),
    );
  }
}
